from PySide2.QtCore import Qt
# 首先导入启动优化器
from startup_optimizer import startup_optimizer

# 新增：设置urllib3连接池大小
import urllib3
urllib3.connectionpool.HTTPConnectionPool.maxsize = 10  # 设置为10或更高
urllib3.connectionpool.HTTPSConnectionPool.maxsize = 10

# 延迟导入其他模块以提高启动速度
import sys
import os

# 使用延迟导入
def get_qt_modules():
    """延迟导入Qt模块"""
    from PySide2.QtWidgets import QApplication
    from PySide2.QtGui import QIcon
    return QApplication, QIcon

def get_main_window():
    """延迟导入主窗口"""
    from main_window import MainWindow
    return MainWindow

def get_pypinyin():
    """延迟导入pypinyin"""
    import pypinyin
    return pypinyin

def resource_path(relative_path):
    """获取打包后资源的绝对路径"""
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    # 特殊处理 pypinyin 资源路径
    if 'pypinyin' in relative_path:
        return os.path.join(base_path, 'pypinyin', os.path.basename(relative_path))
    return os.path.join(base_path, relative_path)

def main():
    print("正在启动程序...")  # 立即输出
    
    # 使用线程异步执行非必要的初始化
    import threading
    
    # 只做必要的Qt优化
    startup_optimizer.optimize_qt_startup()
    
    # 延迟导入其他模块
    QApplication, QIcon = get_qt_modules()
    app = QApplication(sys.argv)
    
    # 异步加载pypinyin资源
    def load_pypinyin_resources():
        pypinyin = get_pypinyin()
        try:
            pypinyin_dir = os.path.dirname(pypinyin.__file__)
            for dict_file in ['pinyin_dict.json', 'phrases_dict.json']:
                dict_path = resource_path(os.path.join(pypinyin_dir, dict_file))
                if os.path.exists(dict_path):
                    pypinyin.load_single_dict(dict_path)
        except Exception as e:
            print(f"pypinyin配置警告: {e}")
    
    # 启动异步加载线程
    threading.Thread(target=load_pypinyin_resources, daemon=True).start()
    
    # 设置应用程序图标
    icon_path = resource_path('blj.ico')
    if os.path.exists(icon_path):
        app.setWindowIcon(QIcon(icon_path))
    
    # 延迟导入主窗口
    MainWindow = get_main_window()
    window = MainWindow()
    
    # 显示启动时间
    startup_optimizer.print_startup_info()
    
    window.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
